﻿using Abp.Extensions;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using WebApiClient.Attributes;
using WebApiClient.Contexts;

namespace ARchGL.Platform.Qianbian
{
    public class DefaultHeaderAttribute : ApiActionFilterAttribute
    {
        private IConfigurationRoot appConfiguration;

        public DefaultHeaderAttribute(IConfigurationRoot _appConfiguration)
        {
            appConfiguration = _appConfiguration;
        }

        public override async Task OnBeginRequestAsync(ApiActionContext context)
        {
            var index = context.RequestMessage.RequestUri.AbsoluteUri.Split("index=")[1];

            var key = appConfiguration[$"Qianbian:KeyId{index}"];
            var secret = appConfiguration[$"Qianbian:Secret{index}"];
            var timestamp = DateTime.Now.ToUnixTimestamp().ToString();
            var code = Guid.NewGuid().ToString("N");
            context.RequestMessage.Headers.Add("keyId", key);
            context.RequestMessage.Headers.Add("ts", timestamp);
            context.RequestMessage.Headers.Add("rcode", code);
            context.RequestMessage.Headers.Add("signature", SHA1(timestamp, code, secret));

            await base.OnBeginRequestAsync(context);
        }

        public override Task OnEndRequestAsync(ApiActionContext context)
        {
            return base.OnEndRequestAsync(context);
        }

        /// <summary>
        /// SHA1 加密
        /// </summary>
        /// <param name="timestamp">时间戳</param>
        /// <param name="code">随机字符串</param>
        /// <param name="secret"></param>
        /// <returns>返回40位大写字符串</returns>
        public static string SHA1(string timestamp, string code, string secret)
        {
            var sha1 = System.Security.Cryptography.SHA1.Create();
            var bytes = sha1.ComputeHash(Encoding.Default.GetBytes($"{code}_{timestamp}_{secret}"));
            return BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant();
        }
    }
}
